#用于处理群聊的消息
import json
import uuid
from datetime import datetime

from Model.default import get_db
from Model.mysocketio.info import Group_Message
from Model.user.User import user_expand, user
from MyRedis.main import get_redis_client

def get_consumer_channel(userid):
    """
    用户一上线就,获取新的信息的消息。通过时间戳,不再使用订阅.socket减少开销,私聊使用socket
    :param userid:
    :return:
    """
    # 采用短轮询方案,减少开销，不适用此函数
    try:
        db=get_db()
        redis_client=get_redis_client()
        if not redis_client:
            raise "redis连接失败"
        userexpand=db.query(user_expand).filter_by(id=userid).first()
        if userexpand:
            for r,c in json.loads(userexpand.room_info or json.dumps({})):
                redis_client.rpush(r,c)

    except Exception as e:
        print(e)

    finally:
        db.close()



async def send_group_message(ws,data,socketpool=None):
    # 关于参数多传,后续再处理
    try:
        db = get_db()
        # 元信息
        room_id=data['room_id']
        sender_id=int(data['sender_id'])
        # 这个未拓展,暂且固定
        message_type=data.get('message_type',"Group_Message")
        content=data.get('content',None)
        timestamp=str(int(datetime.now().timestamp()))
        #持久化
        message=Group_Message(id=str(uuid.uuid4()),
                              timestamp=timestamp,
                              content=content,
                              room_id=room_id,
                              sender_id=sender_id,
                              message_type="Group_Message",
                              )
        db.add(message)
        db.commit()

        redis_client=get_redis_client()
        message_id=redis_client.xadd(room_id,
                          {
                              'message':content,
                              'sender_id':sender_id,
                              'message_type':message_type,
                              'room_type':'group',
                              'room_id':room_id,
                              'sender_username':db.query(user).filter(user.id==sender_id).first().username or '',
                          })
        # message_id用于后续可拓展

        # 可用于拓展业务
        await ws.send_json(
            {
                'type': 'message_callback',
                'status': True,
                'message_type':'Group_Message',
                'data': {
                    'status': True,
                    'sender_id': sender_id,
                    'message_type': message_type,
                    'messages_id': message_id.decode('utf-8'),
                    'room_id': room_id,
                    'room_type':'group'
                }
            }
        )
    except Exception as e:
        print(e)
        db.rollback()
        pass
    finally:
        db.close()

























